import path from 'path';
import { Plugin } from './PluginInterface';
import log from 'electron-log';
import * as fs from 'fs';
import { pathToFileURL } from 'url';
import { PLUGINS_DIR } from './pluginManager';

declare const electronAPI: any;

// 插件缓存
const pluginCache = new Map<string, Plugin>();
// 加载插件
export async function loadPlugin(pluginId: string): Promise<Plugin> {
  if (pluginCache.has(pluginId)) {
    return pluginCache.get(pluginId)!;
  }
  try {
    const pluginPath = path.join(PLUGINS_DIR, pluginId, 'index.ts');
    console.log('插件path：', pluginPath);
    if (!fs.existsSync(pluginPath)) {
      throw new Error(`插件 ${pluginId} 不存在`);
    }

    // 将路径转换为file:// URL并添加查询参数
    const pluginUrl = `${pathToFileURL(pluginPath).href}?ts=${Date.now()}`;
    console.log('插件url：', pluginUrl);
    const pluginModule = await import(pluginUrl);

    if (!pluginModule.default) {
      throw new Error(`插件 ${pluginId} 导出格式不正确`);
    }

    // const plugin = pluginModule.default;
    const plugin = await electronAPI.loadPlugin(pluginId);
    // 验证插件接口
    if (typeof plugin.init !== 'function' || typeof plugin.run !== 'function') {
      throw new Error(`插件 ${pluginId} 缺少必要方法`);
    }
    pluginCache.set(pluginId, plugin);
    return plugin;
  } catch (error: any) {
    log.error(`加载插件 ${pluginId} 失败: ${error.message}`);
    throw error;
  }
}